<template>
  <view class="withdraw-container">
    <!-- 提现金额输入框 -->
    <view class="amount-section">
      <text class="amount-label">提现金额</text>
      <view class="amount-input-wrapper">
        <text class="currency-symbol">¥</text>
        <input 
          type="digit" 
          class="amount-input" 
          placeholder="请输入提现金额" 
          :value="inputAmount" 
          @input="handleInput"
          @confirm="handleInput"
        />
      </view>
	  <text class="available-balance">提现费率：0.005（即0.5%）</text><br />
      <text class="available-balance">可用余额: ¥{{ availableBalance }}</text>
    </view>
    
    
    <!-- 提现按钮 -->
    <button 
      class="withdraw-btn" 
      @click="handleWithdraw"
      :disabled="!isValidAmount"
    >
      提现
    </button>

  </view>
</template>

<script>
	import {
		getuserDalance
	} from '@/api/user.js';	
import { wxExtractCash } from '../../../api/user';
export default {
  data() {
    return {
      inputAmount: '', // 用户输入的提现金额
      availableBalance: 1000.00, // 账户可用余额
      methodIcon: "/static/wechat_icon.png", // 微信图标路径
      bindInfo: "m***o", // 已绑定信息
      errorMsg: '' // 错误提示信息
    };
  },
  computed: {
    // 计算提现金额是否有效
    isValidAmount() {
      if (!this.inputAmount) return false;
      
      const amount = parseFloat(this.inputAmount);
      
      // 验证条件：金额大于0且不超过可用余额
      if (amount <= 0) {
        this.errorMsg = '提现金额必须大于0';
        return false;
      } else if (amount > this.availableBalance) {
        this.errorMsg = '提现金额超过可用余额';
        return false;
      }
      
      this.errorMsg = '';
      return true;
    }
  },
  onLoad(option) {
	this.userDalance();
  },
  methods: {
	  userDalance(){
	  	getuserDalance().then(res=>{
	  		this.availableBalance = res.data.nowMoney;
	  	})
	  },
    // 处理金额输入
    handleInput(e) {
      // 限制只能输入数字和小数点
      let value = e.detail.value;
      value = value.replace(/[^\d.]/g, '');
      
      // 限制只能有一个小数点
      const pointIndex = value.indexOf('.');
      if (pointIndex !== -1) {
        value = value.substring(0, pointIndex + 3); // 保留两位小数
      }
      
      this.inputAmount = value;
    },
    
    changeMethod() {
      // 更换提现方式的逻辑
      uni.showToast({
        title: "点击了更换，可在此写更换逻辑",
        icon: "none",
      });
    },
    
    handleWithdraw() {
		console.log("微信提现")
      if (!this.isValidAmount) return;
      
      const amount = parseFloat(this.inputAmount);
      
      // 显示加载提示
      uni.showLoading({
        title: "提现中...",
      });
	  
	  let value = {};
	  value.name = 'K.'
	  value.money = amount;
      value.extractType = 'weixin';
	  wxExtractCash(value).then(res => {
		  uni.hideLoading();
		  if(res.code == 200) {
			  console.log(res)
				if (wx.canIUse('requestMerchantTransfer')) {
			  // 微信提现
			    wx.requestMerchantTransfer({
			      mchId: '1717161290',
			      appId: 'wxfb5bdc3f4ecb3580',
			      package: res.data.packageInfo,
			      success: (res) => {
			        // res.err_msg将在页面展示成功后返回应用时返回ok，并不代表付款成功
			        console.log('success:', res);
					wx.showToast("申请成功")
					this.inputAmount = '';
			      },
			      fail: (res) => {
			        console.log('fail:', res);
					wx.showToast("申请失败")
			      },
			    });
				} else {
  wx.showModal({
    content: '你的微信版本过低，请更新至最新版本。',
    showCancel: false,
  });
}
		  } else {
			  wx.showModal({
			  	title: '提示',
			  	cancelText: '取消',
			  	confirmText: '确定',
			  	content: res.message,
			  	success(res) {
			  		if (res.confirm) {
						
			  		} else if (res.cancel) {
						
			  		}
			  	}
			  })
			  
		}
	  }).catch(err => {
		  uni.hideLoading();
		return this.$util.Tips({title: err});
		})
      // 模拟提现接口调用
      // setTimeout(() => {
      //   uni.hideLoading();
      //   uni.showToast({
      //     title: `提现申请提交成功，金额：¥${amount.toFixed(2)}`,
      //     icon: "success",
      //     duration: 2000
      //   });
        
      //   // 提现成功后清空输入框
      //   this.inputAmount = '';
      // }, 1500);
    }
  }
};
</script>

<style scoped>
.withdraw-container {
  padding: 15px;
  display: flex;
  flex-direction: column;
  background-color: #fff;
}

.amount-section {
  margin-bottom: 20px;
}

.amount-label {
  font-size: 14px;
  color: #999;
  margin-bottom: 5px;
}

.amount-input-wrapper {
  display: flex;
  align-items: center;
  border-bottom: 1px solid #eee;
  padding-bottom: 5px;
}

.currency-symbol {
  font-size: 20px;
  color: #333;
  margin-right: 5px;
}

.amount-input {
  flex: 1;
  font-size: 20px;
  color: #333;
  height: 30px;
}

.available-balance {
  font-size: 12px;
  color: #666;
  margin-top: 5px;
}

.method-section {
  display: flex;
  align-items: center;
  margin-bottom: 30px;
  margin-top: 20px;
}

.method-icon {
  width: 30px;
  height: 30px;
  margin-right: 10px;
}

.method-text {
  font-size: 16px;
  color: #333;
}

.method-desc {
  font-size: 12px;
  color: #999;
  margin-top: 3px;
  display: block;
}

.change-btn {
  color: #007aff;
  margin-left: 5px;
}

.withdraw-btn {
  background-color: #ff5500;
  color: #000000;
  font-size: 16px;
  padding: 10px;
  border-radius: 5px;
  width: 120px;
  text-align: center;
  /* 修改为居中对齐 */
  margin: 20px auto 0;
}

.withdraw-btn[disabled] {
  background-color: #dcdcdc;
}

.footer-text {
  margin-top: 40px;
  font-size: 12px;
  color: #999;
  text-align: center;
}

/* 错误提示样式 */
.error-msg {
  color: #f56c6c;
  font-size: 12px;
  margin-top: 5px;
}
</style>
